/**
 * @author Jason
 *
 * 2017年7月26日 下午6:38:00
 */
package com.lgd.tools;

/**
 * @author Jason
 *
 */

import java.io.*;
import java.util.Random;

public class ToTxt {


	public static void main(String[] args) throws Exception {
		// 文件存放路径
		String dir = "d:\\FILE\\txt\\";
		Random random = new Random();
		int total = WordBase.WORDS.length;
		// 生成文件数据量
		int fileCount = 10;
		for (int i = 0; i < fileCount; i++) {
			writeFile(dir + createFileName(total, random), createFileContext(total, 10, random));
		}

	}

	/**
	 * 随机生成文件名
	 *
	 * @param total
	 * @param random
	 * @return
	 */
	public static String createFileName(int total, Random random) {
		return WordBase.WORDS[random.nextInt(total)] + ".txt";
	}

	/**
	 * 随机生成文件内容
	 *
	 * @param total
	 * @param wordCount
	 *            文件内容词数
	 * @param random
	 * @return
	 */
	public static String createFileContext(int total, int wordCount, Random random) {

		String content = "";
		for (int i = 0; i < wordCount; i++) {
			content += WordBase.WORDS[random.nextInt(total)] + "\t";
		}
		return content;
	}

	public static void writeFile(String fileName, String fileContent) {
		try {
			File f = new File(fileName);
			if (!f.exists()) {
				f.createNewFile();
			}
			OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
			BufferedWriter writer = new BufferedWriter(write);
			writer.write(fileContent);
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 创建文件
	 *
	 * @param fileName
	 * @return
	 */
	public static boolean createFile(File fileName) throws Exception {
		boolean flag = false;
		try {
			if (!fileName.exists()) {
				fileName.createNewFile();
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	public static String readFile(String filename) {
		String fileContent = "";
		try {
			File f = new File(filename);
			if (f.isFile() && f.exists()) {
				InputStreamReader read = new InputStreamReader(new FileInputStream(f), "gbk");
				BufferedReader reader = new BufferedReader(read);
				String line;
				while ((line = reader.readLine()) != null) {
					fileContent += "\"" + line + "\",";
				}
				read.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileContent;
	}
}